<?php

namespace App\Controller\Api;

use App\Base\BaseController4Api;
use App\Entity\ApiMoney;
use App\Entity\ApiUser;
use App\Model\ApiMoneyTypeModel;
use App\Model\ApiUserModel;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

use Symfony\Component\HttpFoundation\Request;


/**
 * @route("/api")
 */
class ApiUserController extends BaseController4Api
{

    /**
     * @route("/user_create",name="ApiUserCreate")
     */
    public function add()
    {
        $projectId = $this->getProjectId();
        if (!$uid = $this->getParamRequired("uid")) {return $this->json_out(0,"用户ID缺失");}
        $ApiUserModel = new ApiUserModel($this->getDoctrine());
        $ApiUser = $ApiUserModel->getByKV("uid",$uid);
        if (!$ApiUser) {
            //绑定推荐人
            if (!$parent = $this->getParamRequired("parent")) {$parent = 0;}
            $parentStr = "";
            if ($parent) {
                $parentUser = $ApiUserModel->getByKV("uid",$parent);
                if (!$parentUser) {
                    return $this->json_out(0,"推荐人有误");
                }
                $parentStr = $parentUser->getParentstr() ? $parent.",".$parentUser->getParentstr():$parent;
            }

            $ApiUser = new ApiUser();
            $ApiUser->setUid($uid)
                ->setProjectId($projectId)
                ->setParent($parent)
                ->setCat(1)
                ->setParentstr($parentStr);
            $this->myEm()->persist($ApiUser);$this->myEm()->flush();

            //创建用户的原始积分数据
            $ApiMoneyTypeModel = new ApiMoneyTypeModel($this->getDoctrine());
            $MoneyType = $ApiMoneyTypeModel->getByProject($projectId);
            foreach ($MoneyType as $one) {
                $ApiMoney = new ApiMoney();
                $ApiMoney->setProjectId($projectId)
                    ->setUserId($uid)
                    ->setMoney(0)
                    ->setType($one->getProjectId());
                $this->myEm()->persist($ApiMoney);$this->myEm()->flush();
            }
        }else{
            //若果发现用户存在就是在修改上级关系
            if (!$parent = $this->getParamRequired("parent")) {$parent = 0;}
            $parentStr = "";
            if ($parent) {
                $parentUser = $ApiUserModel->getByKV("uid",$parent);
                if (!$parentUser) {
                    return $this->json_out(0,"推荐人有误");
                }
                $parentStr = $parentUser->getParentstr() ? $parent.",".$parentUser->getParentstr():$parent;
            }
            $ApiUser->setUid($uid)
                ->setProjectId($projectId)
                ->setParent($parent)
                ->setParentstr($parentStr);
            $this->myEm()->persist($ApiUser);$this->myEm()->flush();
        }
        return $this->json_out(1,"OK",$this->toArray($ApiUser));
    }

}
